from util import unixtime as epoch
from log import logging

settings = {
  "database": "chess",
  "user": "postgres",
  "password":"admin",
  "host":"localhost"
}

class PostgreSql():
  def __init__(self):
    logging.info("Initializing new pg connection.")
    from psycopg2 import connect as pgconnector
    
    self.connector = pgconnector
    self.__connection = None
    self.__cursor = None
  
  def connect(self):
    logging.info("Setting pg connection..")
    self.__connection = self.connector(**settings)
    self.__cursor = None
    
  @apply
  def connection():
    def fget(self):
      if not self.__connection:
        logging.info("The current connection will be refreshed.")
        self.connect() 
      return self.__connection
      
    return property(**locals())
      
  @apply
  def cursor():
    def fget(self):
      if self.__connection and self.__connection.get_transaction_status()==3:
        logging.info("Transaction is corrupted, rollbacking..")
        self.__connection.rollback()
        
      if not self.__cursor:
        logging.info("Setting pg cursor..")
        self.__cursor = self.connection.cursor()
      
      return self.__cursor
    return property(**locals())
    
pg = PostgreSql()

# converts numeric indexed rows to dictionaries
namedata = lambda values,keys: [ namedata.single(row,keys) for row in values ]
namedata.single = lambda values,keys: dict(zip(keys,values))